﻿namespace ChinaUnicom.Tasks
{
    using ChinaUnicom.Schedule;
    using System;
    using System.Windows;
    using System.Net;

    internal class CreateSessionTask : ITask
    {
        public string Message { get; private set; }

        public CreateSessionTask()
        {
            Message = string.Empty;
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.CreateSession(s =>
            {
                if (s.StatusCode == HttpStatusCode.OK)
                {
                    if (Completed != null)
                    {
                        Completed(this, EventArgs.Empty);
                    }
                }
                else if (s.Exception != null)
                {
                    Message = s.Exception.Message;
                    RaiseFailed();
                }
                else
                {
                    Message = Factory.Parser.Failed(s.Result);
                    RaiseFailed();
                }
            });
        }

        public int Pending { get { return 0; } }

        public event EventHandler Completed;

        public event EventHandler Failed;

        void RaiseFailed()
        {
            if (Failed != null)
            {
                Failed(this, EventArgs.Empty);
            }
        }


        public event EventHandler Started;
    }
}
